//
//  UITableView+wgPlaceholderView.m
//  WGTool
//
//  Created by czw on 2022/8/18.
//

#import "UITableView+wgPlaceholderView.h"
#import <objc/runtime.h>
#import "NSObject+wgSwizzle.h"

static NSString *const placeholderViewKey = @"WG_TableViewPlaceholderViewKey";

static NSString *const isLoadEndDataKey = @"WG_TableViewIsLoadEndDataKey";


@implementation UITableView (wgPlaceholderView)

+(void)load{
    static dispatch_once_t oneToken;
    dispatch_once(&oneToken, ^{
        [self wg_swizzleInstanceSelector:@selector(reloadData) WithSwizzledSelector:@selector(wg_ReloadData)];
    });
}
-(void)wg_ReloadData{
    [self wg_DataEmpty];
    //调回之前的reloadData
    [self wg_ReloadData];
}
- (void)wg_DataEmpty{
    
    BOOL isEmpty = YES;
    id <UITableViewDataSource> ds = self.dataSource;
    NSInteger sections = 1;
    if ([ds respondsToSelector:@selector(numberOfSectionsInTableView:)]) {
        sections = [ds numberOfSectionsInTableView:self];
    }
    for (NSInteger i  = 0; i < sections; i++ ) {
        NSInteger rows  =  [ds tableView:self numberOfRowsInSection:i];
        if (rows) {
            isEmpty = NO;
        }
    }
    if (isEmpty&&self.isLoadEndData) {
        [self.placeholderView removeFromSuperview];
        [self addSubview:self.placeholderView];
    }else{
        [self.placeholderView removeFromSuperview];
    }
}


//分类不能添加成员变量，通过关联对象实现
- (void)setPlaceholderView:(UIView *)placeholderView{
    objc_setAssociatedObject(self, (__bridge const void *)(placeholderViewKey), placeholderView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIView *)placeholderView{
    return  objc_getAssociatedObject(self, (__bridge const void *)(placeholderViewKey));
}

- (void)setIsLoadEndData:(BOOL)isLoadEndData{
    objc_setAssociatedObject(self, (__bridge const void *)(isLoadEndDataKey), [NSNumber numberWithBool:isLoadEndData], OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)isLoadEndData{
    return  ((NSNumber*)objc_getAssociatedObject(self, (__bridge const void *)(isLoadEndDataKey))).boolValue;
}

@end
